package com.zr.task.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.zh.baselibrary.model.TaskModel;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.rxjava.RxJavaHelper;
import com.zh.baselibrary.rxjava.RxSubscribe;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.task.home.ReportVersionBean;
import com.zr.task.activity.WelcomeActivity;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


public class UpdateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")) {
            String packageName = intent.getDataString();
            System.out.println("更新了:" + packageName + "包名的程序");

            Intent intent2 = new Intent(context, WelcomeActivity.class);
            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent2);
            reportVersion(context);
        } else if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
            //安装
            String packageName = intent.getDataString();
            System.out.println("安装了:" + packageName + "包名的程序");
        } else if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
            //接收卸载广播
            String packageName = intent.getDataString();
            System.out.println("卸载了:" + packageName + "包名的程序");

        }

    }


    /**
     * 上传版本号
     *
     * @param context
     */
    public void reportVersion(Context context) {
        TaskModel model = new TaskModel(context);
        model.reportVersion(PhoneUtil.getUUID(context), new ReportVersionBean(3, PhoneUtil.getLocalVersion(context)))
                .subscribeOn(Schedulers.io())//启动订阅线程
                .observeOn(AndroidSchedulers.mainThread())//切换至主线程
                .subscribe(new RxSubscribe<BaseResp<Object>>() {
                    @Override
                    public void onSuccess(BaseResp<Object> objectBaseResp) throws Exception {

                    }

                    @Override
                    public void onHint(String hint) {
                        ToastView.showLong("上报版本号失败"+hint);
                    }
                });
    }
}
